using UnityEditor;
using UnityEngine;

namespace FormicArch.AssetBundleEditor
{
    public class CommonDependency : AssetDependency
    {
        public CommonDependency(string path, IAssetBuildManager manager, bool isMainAsset=false) : base(path, manager,isMainAsset)
        {
            SetMainAsset();
            SetDependency();
        }

        private void SetMainAsset()
        {
            if (!Manager.TryGetDependencyValue(AssetPath, out _))
            {
                Manager.AddDependency(AssetPath, this);
            }
        }
        
        public override void SetDependency()
        {
            var dependencies = Manager.GetDependencies(AssetPath);
            foreach (var dependencyPath in dependencies)
            {
                if (AssetDatabase.IsValidFolder(dependencyPath))
                {
                    continue;
                }

                if (!Manager.TryGetDependencyValue(dependencyPath, out var dependency))
                {
                    dependency = new CommonDependency(dependencyPath, Manager,Manager.IsMainAsset(dependencyPath));
                }
                dependency.AddDependencyOn(this);
                AddDependency(dependency);
            }
        }

        public override string ToString()
        {
            return $"{base.ToString()}:【{AssetPath}】";
        }
    }
}